package com.qumitech.visualnovel.controller.rest;

import com.alibaba.fastjson.JSONObject;
import com.qumitech.visualnovel.component.util.CommonUtil;
import com.qumitech.visualnovel.model.common.BaseResponse;
import com.qumitech.visualnovel.model.dao.console.VisualSearchRecord;

import com.qumitech.visualnovel.service.virtualSearch.VisualSearchService;
import com.qumitech.visualnovel.service.virtualSearch.VisualSearchTask;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;

@RestController
@RequestMapping("/api/visualSearch")
public class VisualSearchController {

    @Autowired
    VisualSearchService visualSearchService;

    @Autowired
    private VisualSearchTask visualSearchTask;

    @RequestMapping(value = "/ConnectionOptions",method  = RequestMethod.GET)
    public JSONObject PropertyOptions(){
        List<HashMap<String,Object>> list=visualSearchService.databaseOption();
        BaseResponse results = new BaseResponse(list);
        return results;
    }

    @RequestMapping(value="/addTask", method = RequestMethod.POST)
    public JSONObject addTask(@RequestBody JSONObject param) {
        JSONObject data = new JSONObject();
        String sql = param.getString("taskSql");
        String []filters = {"insert ", "replace ", "delete ", "drop ", "create "};
        for(String  filter: filters){
            if (sql.contains(filter))
            {
                return new BaseResponse(-1, "添加失败，包含敏感字符串", data);
            }
        }
        VisualSearchRecord visualSearchRecord = visualSearchService.addTask(param);
        visualSearchTask.executeTask(visualSearchRecord);
        return new BaseResponse(0, "已经提交任务，请前往下载列表页面查看", data);
    }


    @RequestMapping(value="/list", method = RequestMethod.GET)
    public JSONObject getList(@RequestParam(value="id",required=false) Integer id,
                              @RequestParam(value="title",required=false) String title,
                              @RequestParam(value="status",required=false) Integer status,
                              @RequestParam(value="startTime",required=false) String startTime,
                              @RequestParam(value="endTime",required=false) String endTime,
                              @RequestParam(value="offset", required=false, defaultValue="0") int offset,
                              @RequestParam(value="limit", required=false, defaultValue="20") int limit,
                              @RequestParam(value="orderType", required=false, defaultValue="DESC") String orderType,
                              @RequestParam(value="orderBy", required=false, defaultValue="updatedAt") String orderBy) {
        orderBy = String.valueOf(CommonUtil.camelToUnderline(new StringBuffer(orderBy)));
        int count = visualSearchService.getCount(id, title, status, startTime, endTime);
        List<VisualSearchRecord> list = visualSearchService.getList(id, title, status, startTime, endTime, offset,limit,orderBy,orderType);
        BaseResponse results = new BaseResponse<>(list,count);
        return results;
    }

    @RequestMapping(value="/download", method = RequestMethod.GET)
    public void TaskDownload(HttpServletResponse response, @RequestParam(value="id") Integer id) {
        VisualSearchRecord visualSearchRecord = visualSearchService.findVisualSearchRecordById(id);
        String filePath = visualSearchRecord.getDownload();
        String suffix = filePath.substring(filePath.lastIndexOf("/")+1);
        response.setContentType("application/octet-stream;charset=UTF-8");
        try {
            response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(suffix, "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        try {
            CommonUtil.getDownload(response, filePath);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
